package thread;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map.Entry;
import object.Command;
import object.Command.CommandType;
import object.Dialogue;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import util.CommandManager;
import voice.main.ChatActivity;
import voice.main.ChatFragment;
import android.os.AsyncTask;
import android.util.Log;

public class RetrieveAIMLTask extends AsyncTask<String, String, String> {
	private ChatFragment context;
	public RetrieveAIMLTask(ChatFragment context) {
		this.context = context;
		Log.v("Constructor", "Begin Constructor");
    }
	
    protected String doInBackground(String... question) {
		try {
			Log.v("Background", "Begin background");
	    	HttpClient httpClient = new DefaultHttpClient();
	    	String url;
			url = Command.serverAddress + "/VoiceServer/aiml/" + URLEncoder.encode(question[0], "UTF-8");
	    	HttpGet httpGet = new HttpGet(url);
    	    HttpResponse response = httpClient.execute(httpGet);
    	    StatusLine statusLine = response.getStatusLine();
    	    if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    	        HttpEntity entity = response.getEntity();
    	        ByteArrayOutputStream out = new ByteArrayOutputStream();
    	        entity.writeTo(out);
    	        out.close();
    	        String responseStr = out.toString();
    	        return responseStr;
    	    } else {
    	    	return "Bad Response.";
    	    }
		} 
		catch (UnsupportedEncodingException e1) {
	    	return "Encoding UTF-8 is not supported.";
		}
		catch (ClientProtocolException e) {
	    	return "Failed to connect to server. (HTTP Protocol Error)";
    	} 
		catch (IOException e) {
	    	return "Failed to connect to server. (Connection Aborted)";
    	}
    }
    protected void onPostExecute(String answer) {

    	Log.v("Post", "Post execute");
    	ChatActivity activity = (ChatActivity) context.getActivity();
    	
    	CommandManager commandManager = CommandManager.getInstance(activity.getApplicationContext());
    	if (answer.contains("[COMMAND]")) {
    		answer = answer.substring(answer.indexOf("[COMMAND]")+9).trim();
    		String data = "";
    		if (answer.contains("[DATA]")) {
    			data = answer.substring(answer.indexOf("[DATA]")+6).trim();
    			answer = answer.substring(0, answer.indexOf("[DATA]")).trim();
    		}
        	for (Entry<CommandType, Command> entry : commandManager.commandsList.entrySet()) {
        		for (int i=0; i<entry.getValue().commands.size(); i++) {
        			if (entry.getValue().commands.get(i).equalsIgnoreCase(answer)) {
        				commandManager.executeCommand(context.getActivity().getApplicationContext(), entry.getKey(), data);
        	        	context.adapter.add(new Dialogue(false, entry.getValue().response));
        	    		new TextToSpeechTask(activity).execute(entry.getValue().response);
        	    		return;
        	    	}	
        		}
        	}
    	}
    	else {
        	context.adapter.add(new Dialogue(false, answer));
        	new TextToSpeechTask(activity).execute(answer);
    	}
    }

 }
